package pers.qianyu.month_202101.date_20210118;

import java.util.*;

/**
 * 151. 翻转字符串里的单词
 * https://leetcode-cn.com/problems/reverse-words-in-a-string/
 *
 * @author mizzle rain
 * @date 2021-01-18 10:54
 */
public class ReverseWords {
    public String reverseWords(String s) {
        s = s.trim();
        s += " ";
        Deque<String> q = new LinkedList<>();
        char[] arr = s.toCharArray();
        int start = 0;
        int len = arr.length;
        for (int i = 0; i < len; i++) {
            if (arr[i] == ' ') {
                q.addLast(new String(arr, start, i - start));
                while (i < len && arr[i] == ' ') {
                    i++;
                }
                start = i;
            }
        }
        StringBuilder builder = new StringBuilder();
        while (!q.isEmpty()) {
            builder.append(q.pollLast() + " ");
        }
        return builder.deleteCharAt(builder.length() - 1).toString();
    }
}
